
package cz.muni.fi.heathtow.web.validation;

import cz.muni.fi.heathrowapi.AircraftService;
import cz.muni.fi.heathrowapi.dto.AircraftDTO;
import java.util.List;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;

/**
 *
 * @author Jan Richter
 */
public class UniqueAircraftCodeValidator implements IValidator<String> {
    @SpringBean(name="aircraftService")
    private AircraftService aircraftService;
    private Long ignoreId;
    private List<AircraftDTO> aircrafts;
    
    public UniqueAircraftCodeValidator() {
        Injector.get().inject(this);
        aircrafts = aircraftService.findAll();
    }
    
    public UniqueAircraftCodeValidator(Long id) {
        Injector.get().inject(this);
        ignoreId = id;
        aircrafts = aircraftService.findAll();
    }
    
    
    @Override
    public void validate(IValidatable<String> iv) {
        for(AircraftDTO aircraft : aircrafts){
            if(aircraft.getCode().equals(iv.getValue()) && !aircraft.getId().equals(ignoreId)){
                error(iv, "notUnique");
                break;
            }
        }
    }
    
    private void error(IValidatable<String> validatable, String errorKey) {
        ValidationError error = new ValidationError();
        error.addMessageKey(errorKey);
        validatable.error(error);
    }
}
